package com.example.projects;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import android.os.AsyncTask;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.*;

public class UpdateCommentDatabase extends AsyncTask<String, Void, Integer> {
    private Context mContext;
    private ProgressDialog dialog;
    private String barcode;
    private String file;
    private HttpClient httpClient=null;
    
    public UpdateCommentDatabase(Context c) {
            this.mContext = c;
    }
    
    @Override
    protected void onPreExecute() {
            dialog = ProgressDialog.show(this.mContext, "", 
            "Sending your review to the server. Please wait...", true);
    }
    
    @Override
    protected void onPostExecute(Integer r) {
    	safeClose(httpClient);
    	AlertDialog.Builder alertBuilder = new AlertDialog.Builder(mContext);
    	alertBuilder
    		.setTitle("Error")
    		.setCancelable(false)
    		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();							
				}
			});
    	AlertDialog alert;
            dialog.dismiss();
            switch(r) {
            case 0: System.out.println("Hey stuff worked.");
	        	AccessDatabase ad = new AccessDatabase(mContext);
	        	ad.execute(barcode, file, "comment");
	            break;
            case 1: 
	            alertBuilder.setMessage("Could not connect to product database.  Try again later.");
	            alert = alertBuilder.create();
	        	alert.show();
                break;
            case 2: 
	            alertBuilder.setMessage("Connection to product database timed out.  Try again later.");
	        	alert = alertBuilder.create();
	        	alert.show();
                break;
            case 3: 
	            alertBuilder.setMessage("Unsupported character in barcode.  Check barcode and try again.");
	            alert = alertBuilder.create();
	        	alert.show();
                break;
            default: System.out.println("Oops, something unexpected happened.");
                    break;
            }
    }
    
    
    @Override
    public Integer doInBackground(String... args) {
    	barcode = args[0];
    	file = args[5];
    //public void getData(String contents, String path){
	    try {
	        //Connect to server for product info
	        httpClient = new DefaultHttpClient();
	        // set timeout 3 seconds this may require changing
	        HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
	        String url = "http://www.cpt3004.dynalias.org:81/cpt/phpappfixed/insertcomment.php";
	        HttpPost httpPost = new HttpPost(url);
	        List<NameValuePair> pairs = new ArrayList<NameValuePair>();  
	        pairs.add(new BasicNameValuePair("productid", args[0]));
	        pairs.add(new BasicNameValuePair("review", args[1]));
	        pairs.add(new BasicNameValuePair("rating", args[2]));
	        pairs.add(new BasicNameValuePair("fbid", args[3]));
	        pairs.add(new BasicNameValuePair("fbname", args[4]));
	        httpPost.setEntity(new UrlEncodedFormEntity(pairs));
	        httpClient.execute(httpPost);
	        safeClose(httpClient);
	    } catch (UnsupportedEncodingException e1) {
	    	safeClose(httpClient);
            // TODO Auto-generated catch block
            System.out.println("Unsupported");
            e1.printStackTrace();
            return 3;
	    } catch (IOException e) {
	    	safeClose(httpClient);
            System.out.println("I/O exception accessing database");
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 1;
	    }
	   	return 0;
    	//ConnectionManager.getInstance().didComplete(this);
    }
    
    private void safeClose(HttpClient client) {
        if(client != null && client.getConnectionManager() != null)
        {
            client.getConnectionManager().shutdown();
        }
    }
}
